<template>
  <base-layout
    :dialog-title="dialogTitle"
    :dialog-visible="dialogVisible"
    @dialog-close="dialogClose"
    :dialogWidth="dialogWidth"
  >
    <template #searchPanel>
      <el-form ref="fromdata1" :model="formData" label-width="90px">
        <el-row>
          <el-col :span="12">基本信息</el-col>
          <el-divider content-position="center"></el-divider>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-row>
              <el-col :span="12">
                <el-form-item label="配车门店:" prop="storeId">
                  <JobShop
                    clearable
                    v-model="formData.storeId"
                    class="w-100"
                    @input="sotreChange"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="合同分类:" prop="contractTypeDictId">
                  <el-select
                    clearable
                    v-model="formData.contractTypeDictId"
                    placeholder="请选择合同分类"
                    class="w-100"
                  >
                    <el-option
                      v-for="item in contractDict['合同分类']"
                      :key="item.index"
                      :value="item.value"
                      :label="item.text"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="供应商:" prop="supplierId">
                  <el-select
                    clearable
                    v-model="formData.supplierId"
                    placeholder="请选择供应商"
                    class="w-100"
                  >
                    <el-option
                      v-for="item in supplierOptions"
                      :key="item.id"
                      :value="item.id"
                      :label="item.supplierName"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="合同日期:" prop="contractTime">
                  <el-date-picker
                    v-model="formData.contractTime"
                    style="width: 209px"
                    type="datetime"
                    value-format="yyyy-MM-dd hh:mm:ss"
                    class="w-100"
                    placeholder="请选择合同日期"
                  ></el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="税率:" prop="rate">
                  <el-input
                    clearable
                    v-model.number="formData.rate"
                    class="w-100"
                    type="number"
                  >
                    <template slot="append">%</template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="12">
            <el-row>
              <el-col :span="24">
                <el-form-item label="备注:" prop="remark">
                  <el-input
                    type="textarea"
                    clearable
                    v-model="formData.remark"
                    class="w-100"
                    placeholder="合同备注"
                    :rows="6"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
      </el-form>
    </template>
    <template #contentPanel>
      <el-row>
        <el-col :span="12">车型信息</el-col>
        <el-col :span="12" class="text-right">
          <el-button type="primary" @click="addCarModel"
            ><i class="el-icon-plus"></i>添加车型信息</el-button
          >
        </el-col>
      </el-row>
      <el-divider content-position="center"></el-divider>
      <data-table
        :value="formData.contractCarList"
        :has-action="true"
        :table-column-attributes="tableColumnAttributes"
        :width="160"
        :isShowPage="false"
      >
        <template #action="{ row }">
          <i
            class="el-icon-delete"
            title="删除"
            style="color: red; margin-left: 15px; cursor: pointer"
            @click="deleteSelectCarModel(row)"
          ></i>
        </template>
      </data-table>
      <el-row slot="allNum">
        <div class="total-count">
          总金额:<span class="money-value">￥{{ formData.amount }}</span>
          总数:<span class="count-value">{{ formData.total }}</span>
        </div>
        <el-col :span="24" align="right" justify="center">
          <el-button
            v-permission="!$route.params.id ? authConfig.add : authConfig.edit"
            type="success"
            @click="saveUpdate"
            >保存</el-button
          >
        </el-col>
      </el-row>
    </template>
    <template #dialog>
      <SelectCarModel @getList="addCarModelBack" :store-id="formData.storeId" />
    </template>
  </base-layout>
</template>

<script>
import {
  updateData,
  addData,
  details,
  getSupplierByStorId,
  findById,
} from '@/api/pre-sale/newCarStock/carMatchingContract'
import baseMixin from '@/mixins/base'
import { getDict, parseTimeToYMDHMS } from '@/utils'
import { SelectCarModel } from '@/components/index'

// import { rulesForm } from './rules'

export default {
  components: { SelectCarModel },
  computed: {
    tableDataMap() {
      const map = {}
      this.formData.contractCarList.forEach((item, index) => {
        map[item.id] = index
      })
      return map
    },
  },
  mixins: [
    baseMixin({
      addData: addData,
      updateData: updateData,
      format(res) {
        return res.map((data) => {
          return data
        })
      },
    }),
  ],
  data() {
    return {
      authConfig: {
        add: 'contract:create',
        edit: 'contract:update',
      },
      dialogVisible: false,
      dialogTitle: '车型选择',
      dialogWidth: '1000px',
      approvalData: null,
      detailData: null,
      isFirstEdit: false,
      formData: {
        id: '',
        storeId: '',
        contractTypeDictId: '', // 合同分类
        supplierId: '', // 供应商
        contractTime: '', // 合同日期
        remark: '', // 备注
        rate: '', // 税率
        contractCarList: [],
        amount: 0, // 总金额
        total: 0, // 总数
      },
      supplierOptions: [],
      contractTypeOptions: [], // 合同分类
      contractDict: [],
      tableColumnAttributes: [
        {
          name: '品牌',
          value: 'brandName',
          type: 'text',
        },
        {
          name: '车系',
          value: 'seriesName',
          type: 'text',
        },
        {
          name: '车型',
          value: 'modelName',
          type: 'text',
        },
        {
          name: '车身颜色',
          value: 'outColor',
          type: 'input',

        },
        {
          name: '内饰颜色',
          value: 'inColor',
          type: 'input',
        },
        {
          name: '车顶色',
          value: 'roofColor',
          type: 'input',
        },
        {
          name: '数量',
          value: 'num',
          type: 'inputNumber',
          action: this.calcData,
        },
        {
          name: '付款日期',
          value: 'paymentTime',
          type: 'date',
        },
        {
          name: '标准进价',
          value: 'criterionPrice',
          type: 'text',
        },
        {
          name: '实际进价',
          value: 'realityPrice',
          type: 'inputNumber',
          action: this.calcData,
        },
        {
          name: '资金来源',
          value: 'capitalSourceDictId',
          type: 'select',
          multiple: true,
          options: getDict(['资金来源'])['资金来源'].map((item) => {
            return { id: item.value+'', value: item.text }
          }),
        },
        {
          name: '资金利息',
          value: 'zjlxId',
          type: 'select',
          options: [],
        },
      ],
      approvalData: [],
    }
  },
  methods: {
    // 门店切换
    sotreChange(newValue) {
      if (!newValue) {
        return
      }
      if (this.isFirstEdit) {
        this.isFirstEdit = false
      } else {
        this.formData.supplierId = ''
        this.formData.contractTypeDictId = ''
        // 清楚资金利息
        this.tableColumnAttributes[11].options = []
        this.formData.contractCarList = this.formData.contractCarList.map(
          (item) => {
            return {
              ...item,
              zjlxId: '',
            }
          }
        )
      }
      // 查询供应商
      this.getSupplierFun()
      this.getMoneyInterest()
      this.contractDict = getDict(['合同分类'], this.formData.storeId)
    },
    // 添加车型模态框
    addCarModel() {
      if (!this.formData.storeId) {
        this.$message.error('请选择配车门店后添加车型')
        return
      }
      this.dialogVisible = true
    },

    // 计算当前数据
    calcData(row) {
      const { num, realityPrice } = row
      row.amount = num * realityPrice
      this.calcCountData()
    },
    // 统计所有数据
    calcCountData() {
      let amount = 0 // 总金额
      let total = 0 // 总数量

      this.formData.contractCarList.forEach((item) => {
        amount += parseInt(item.amount) || 0
        total += parseInt(item.num) || 0
      })
      this.formData.amount = amount
      this.formData.total = total
      this.$forceUpdate()
    },

    // 监听添加车型结果
    addCarModelBack(selection) {
      const tableList =[]
     
      selection.forEach((item) => {
        if (!this.tableDataMap[item.id]) {
          console.log(item)
          tableList.push({
            ...item,
          // id: item.id,
          carBrandId: item.brandId, // 品牌id
           //carBrandName: item.brandName,
           //seriesId: item.seriesId, //车系
          //  carSeriesName: item.seriesName,
            modelId: item.id, // 车型
          //  carModelName: item.modelName,
          //  engineModel: '', // 发动机型号
          //  modelInfo: '', //车型细分
            // outColor: '', //车身色
            // inColor: '', //内饰色
            // roofColor: '', //车顶色
           // paymentTime: '', //付款时间
           num:1,
            criterionPrice: item.guidePrice,//(item.guidePrice.split('')).includes('万')?(+item.guidePrice.replace(/万/g,'')*10000):item.guidePrice, //标准进价
            realityPrice: 0, //实际进价
            capitalSourceDictId:[], //资金来源
           // zjlxId: '', // 资金利息
          })
        }
      })
      this.formData.contractCarList.push(...tableList)
      this.dialogVisible = false
    },

    dialogClose() {
      this.dialogVisible = false
    },

    // 新增
    saveUpdate() {
      this.$refs['fromdata1'].validate((valid) => {
        if (valid) {
          let options = this.formData
          options.contractTime = options.contractTime
            ? parseTimeToYMDHMS(options.contractTime)
            : ''
          this.saveSuppierData()
        }
      })
    },

    async saveSuppierData() {
      this.formData.contractCarList.forEach(item => {
        item.capitalSourceDictId = item.capitalSourceDictId.join(',')
      })
      const { success } = this.formData.id
        ? await updateData(this.formData)
        : await addData(this.formData)
      if (success) {
        this.$message({
          message: '操作成功',
          type: 'success',
        })
        this.$router.push({ path: '/newCarStock/carMatchingContract' })
      } else {
        this.$message.error('操作失败')
      }
    },

    //查询供应商
    async getSupplierFun() {
      let { data } = await getSupplierByStorId(
        this.formData.storeId,
        '整车供应商'
      )
      this.supplierOptions = data
    },
    //查询资金利息
    async getMoneyInterest() {
      let { data } = await findById(this.formData.storeId)
      this.tableColumnAttributes[11].options = data.map((item) => {
        return { id: item.id, value: item.name }
      })
    },

    // 查询详情
    async detail(id) {
      let { data } = await details(id)
      data.contractCarList.map(item=>{
        item.capitalSourceDictId=item.capitalSourceDictId.split(',')
      })
      console.log(data.contractCarList)
      this.formData = data
      this.getSupplierFun()
      this.contractDict = getDict(['合同分类'], this.formData.storeId)
    },

    // 删除加入的车型
    deleteSelectCarModel(row) {
      this.formData.contractCarList = this.formData.contractCarList.filter(
        (res) => {
          return res.id !== row.id
        }
      )
    },
  },
  created() {
    const id = this.$route.query && this.$route.query.id
    if (id) {
      this.formData.id = id
      this.isFirstEdit = true
      this.detail(id)
    }
  },
  mounted() {},
}
</script>

<style lang="scss" scoped>
/deep/ {
  .el-input__inner {
    padding-right: 30px;
  }
}
</style>
